package com.timmy.smarttest.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.inuker.bluetooth.library.search.SearchResult;
import com.timmy.smarttest.R;
import com.timmy.smarttest.adapter.ConnectsAdapter;
import com.timmy.smarttest.adapter.ResultsAdapter;
import com.timmy.smarttest.presenter.InfoActivityPresenter;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class InfoActivity extends AppCompatActivity {

    private static final String TAG = InfoActivity.class.getSimpleName();
    @BindView(R.id.listview_results)
    ListView mListviewResults;
    @BindView(R.id.listview_connect)
    ListView mListviewConnect;
    @BindView(R.id.tv_ble_state)
    TextView mTvBleState;
    @BindView(R.id.tv_present)
    TextView mTvPresent;
    @BindView(R.id.btn_start_test)
    Button mBtnStartTest;

    private int OPEN_REQUEST_CODE = 821;
    private InfoActivityPresenter mPresenter;
    private ProgressDialog mProgressDialog;
    private ResultsAdapter mResultsAdapter;
    private ConnectsAdapter mConnectsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);
        ButterKnife.bind(this);

        mPresenter = new InfoActivityPresenter(this);
        // 检测蓝牙是否开启
        boolean bluetoothOpened = mPresenter.mBleUtil.isBluetoothOpened();

        if (!bluetoothOpened) {
            // 申请打开蓝牙
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, OPEN_REQUEST_CODE);
        }

        initView();
        initListener();
    }

    private void initView() {
        // 初始化各种View
        mResultsAdapter = new ResultsAdapter(this);
        mListviewResults.setAdapter(mResultsAdapter);

        // 初始化各种View
        mConnectsAdapter = new ConnectsAdapter(this);
        mListviewConnect.setAdapter(mConnectsAdapter);
    }

    private void initListener() {
        mListviewResults.setOnItemClickListener(mResultsListener);
        mListviewConnect.setOnItemClickListener(mConnectsListener);
    }

    private void scanBleDevice() {
        mPresenter.registerNotifyListener();
        mPresenter.scanBleDevice();
    }

    // 连接成功
    public void onConnectSucc() {
        mTvBleState.setText("蓝牙连接成功");
        hideProgressDialog();
    }

    // 更新adapter
    public void upData(List<SearchResult> mResults, List<SearchResult> mConnectList) {
        mResultsAdapter.setData(mResults);
        mConnectsAdapter.setData(mConnectList);
    }

    // 连接失败
    public void onConnectFaild() {
        mBtnStartTest.setText("开始测试");
        mTvBleState.setText("蓝牙未连接");
        checkId = 1;
        mTvPresent.setText("");

        mTvPresent.setTextColor(tvColorBlack);
        hideProgressDialog();
    }

    private void showToast(String text) {
        Toast.makeText(InfoActivity.this, text, Toast.LENGTH_SHORT).show();
    }

    public void getDevice() {
        hideProgressDialog();
    }


    @OnClick({R.id.btn_start_test, R.id.btn_scan, R.id.dis_connect, R.id.shangyixian})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_start_test:

                mBtnStartTest.setClickable(false);
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mBtnStartTest.setClickable(true);

                    }
                }, 1000);

                boolean bleState = mPresenter.getBleState();
                if (bleState) {
                    if (checkId == 7) {
                        // 断开蓝牙连接
                        mPresenter.disConnect();
                        checkId = 1;
                    } else {
                        mBtnStartTest.setText("下一项");
                        startTest();
                    }

                } else {
                    showToast("蓝牙未连接");
                }
                break;
            case R.id.btn_scan:
                showProgressDialog("扫描设备", "正在扫描...");
                scanBleDevice();
                break;
            case R.id.dis_connect:
                mPresenter.disConnect();
                break;
            case R.id.shangyixian:

                if (checkId == 1) {
                    Toast.makeText(this, "当前已经是第一项了", Toast.LENGTH_SHORT).show();
                } else {

                    if (mPresenter.getBleState()) {
                        startTest2();
                    } else {
                        showToast("蓝牙未连接");
                    }

                }

                break;
        }
    }

    private void startTest2() {
        checkId--;

        // 先暂停当前的 然后发送上一个
        mPresenter.sendPauseData(checkId);

        mPresenter.sendData(checkId - 1);
        mHandler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        mTvPresent.setText(proofTestValue(checkId - 1));
                        //checkId--;
                    }
                }, 500);

    }

    // 开始测试
    private void startTest() {

        // 如果是第一个 则不用发送停止指令, 如果不是第一个 则首先发送停止指令  然后再发送 下一个的开始指令
        if (checkId != 1) {
            // 先发送一个暂停
            mPresenter.sendPauseData(checkId - 1);
        }

        // 在开始下一个指令
        mPresenter.sendData(checkId);
        mHandler.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        mTvPresent.setText(proofTestValue(checkId));
                        checkId++;
                    }
                }, 500);
    }


    private android.os.Handler mHandler = new android.os.Handler();

    private void showProgressDialog(String title, String message) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog.show(InfoActivity.this, title, message, false);
        } else if (mProgressDialog.isShowing()) {
            mProgressDialog.setTitle(title);
            mProgressDialog.setMessage(message);
        }
        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }


    // ========================== 监听点击事件
    AdapterView.OnItemClickListener mResultsListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // 判断设备是否有在连接,有的话 先断开连接
            boolean bleState = mPresenter.getBleState();

            if (bleState) {
                showToast("蓝牙已连接连接,请先断开蓝牙连接");
            } else {
                showProgressDialog("连接设备", "正在连接...");
                SearchResult item = (SearchResult) mResultsAdapter.getItem(position);
                // 点击开始连接设备
                mPresenter.connectDevice(item);
            }
        }
    };

    AdapterView.OnItemClickListener mConnectsListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // 移除已经连接的设备, 添加到搜索列表中
            SearchResult item = (SearchResult) mConnectsAdapter.getItem(position);
            mPresenter.mConnectList.remove(item);
            mResultsAdapter.addData(item);
            mConnectsAdapter.removeData(item);
        }
    };

    private int checkId = 1;

    private String proofTestValue(int checkedId) {

        String checkText = "";

        switch (checkedId) {
            case 1:
                checkText = "LED灯";
                break;
            case 2:
                checkText = "马达";
                break;
            case 3:
                checkText = "温湿度 紫外线";
                break;
            case 4:
                checkText = "心率";
                break;
            case 5:
                checkText = "陀螺仪 \n 注意 \n 请将设备静止一秒以上";
                break;
            case 6:
                mBtnStartTest.setText("断开蓝牙连接");
                checkText = "VOC \n 注意 \n 请对设备侧面的开口处吹气";
                break;
            case 7:
                checkText = "VOC校准";
                mTvPresent.setText("VOC校准");
                break;
        }

        return checkText;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OPEN_REQUEST_CODE) {
            // 打开蓝牙了
            if (resultCode == Activity.RESULT_OK) {
                // 打开了蓝牙了
                showToast("蓝牙已打开");
            } else if (resultCode == Activity.RESULT_CANCELED) {
                showToast("权限被拒绝了");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.disConnect();
    }

    // 心率值
    public void onHeartRateRecieved(int currentHeartRate) {
        String text = "心率 \n 心率值: " + currentHeartRate;
        mTvPresent.setText(text);
    }

    // 温湿度 紫外线
    public void onEnMeasureDataRecieved(int tempState, int temp, int shidu, int ziwaixian) {
        String text = "温湿度,紫外线 \n 温度正负值: " + tempState + "\n 温度: " + temp + "℃\n 温湿度: " + shidu + "\n紫外线: " + ziwaixian;
        mTvPresent.setText(text);
    }

    // voc
    public void onVOCMeasureData(float jiaquan, int tvoc, int co2) {
        Log.i(TAG, "jiaquan: " + jiaquan);
        Log.i(TAG, "tvoc: " + tvoc);
        Log.i(TAG, "co2: " + co2);

        String text = "VOC \n 甲醛: " + jiaquan + "\n tvoc " + tvoc + "\n 二氧化碳: " + co2;
        mTvPresent.setText(text);
    }

    public void onVOCMeasureData(byte b) {

        String text = "";

        if (b == 01) {
            text = "VOC检测正常";
        } else if (b == 0) {
            text = "VOC检测不正常";
        }

        mTvPresent.setText("VOC\n" + text);
    }

    public void setGyroscopeAlertDialog1() {
        mTvPresent.setText("陀螺仪 \n 注意 \n 请将设备静止一秒以上");
        mTvPresent.setTextColor(tvColorRed);
        mPresenter.startTestGyroscope();
    }

    private int tvColorRed = 0xFFFF0000;
    private int tvColorBlack = tvColorRed;


    public void setVocAlertDialog() {
        mTvPresent.setText("VOC \n 注意 \n 请对设备侧面的开口处吹气");
        mTvPresent.setTextColor(tvColorRed);
        mPresenter.startTestVoc();
    }

    public void onGyroscope(byte data1, byte flag, byte sign) {
        /***
         * 1 静止一秒
         *         90 00 0 00 000 00 0 00
         *
         *  等待   90  01 01 00 000
         * 2. 显示 请晃动设备
         *
         * 等待 a9 90 01 01 01 00 00 0
         *
         * 3.1 显示设备正常
         *
         * 3.2     90 01 00 00 00
         *  设备不正常
         *
         *
         */

        if (data1 == 01) {
            if (flag == 01 && sign == 0) {
                //晃动设备
                mTvPresent.setText("陀螺仪\n请在3s内摇动设备");
            } else if (flag == 01 && sign == 1) {
                // 显示设备正常

                mTvPresent.setText("陀螺仪 \n 设备正常");
            } else if (flag == 00 && sign == 1) {
                // 显示设备正常
                mTvPresent.setText("陀螺仪 \n 设备不正常");
            }
        }

    }
}
